import axios from "axios";
import { ElMessage } from "element-plus";
import userStore from "@/store/user";
import { storeToRefs } from "pinia";
const { isSend } = storeToRefs(userStore());
//axios基础封装
const Service = axios.create({
  // 根域名
  baseURL: import.meta.env.VITE_BASE_API,
  // 超时设置
  timeout: 5000,
  withCredentials: true, // 允许携带 Cookie
});

Service.interceptors.request.use(
  (config) => {
    isSend.value = true;
    return config;
  },
  (error) => {
    console.log(error);
    isSend.value = false;
    return Promise.reject(error);
  }
);

Service.interceptors.response.use(
  (res) => {
    console.log(res);
    isSend.value = false;
    return res.data;
  },
  (err) => {
    let message = "";
    console.error(err);
    const status = err.response.status;
    isSend.value = false;
    switch (status) {
      case 401:
        message = "Token过期";
        break;
      case 403:
        message = "无权访问";
        break;
      case 404:
        message = "请求地址错误";
        break;
      case 405:
        message = "方法不被允许";
        break;
      case 500:
        message = "服务器错误";
        break;
      default:
        message = err.response.data.error;
        break;
    }
    ElMessage({
      type: "error",
      message,
    });
    if (status === 401) {
      location.href = "/login";
    }
    return Promise.reject(new Error(err.response.message));
  }
);

export default Service;
